package com.gdk.ksoft.assembly.utils.extensions;

import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Created by Mrper on 2014/12/27.
 * 控件辅助类
 */
public class ControlUtils {

    /**
     * 获取文字控件中的字符串并转化为数字字符串
     * @param txtView
     * @return
     */
    public static String getNumberStringFromTextView(TextView txtView){
        CharSequence cs = txtView.getText();
        if(cs.length()<=0) return "0";
        String str = cs.toString();
        if(TextUtils.isEmpty(str)||str.equals("-")||str.equals("."))
            str = "0";
        else if(str.matches("^\\.\\d+$"))
            str = "0" + str;
        return str;
    }

    /**
     * 设置列表的高度
     * @param listView
     */
    public static void setListViewHeightBasedOnChildren(ListView listView) {
        //获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }

        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {   //listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);  //计算子项View 的宽高
            totalHeight += listItem.getMeasuredHeight();  //统计所有子项的总高度
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        //listView.getDividerHeight()获取子项间分隔符占用的高度
        //params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }

    /**
     * 显示Toast提示框
     * @param context
     * @param message
     * @param gravity
     * @param duration
     */
    public static void showToast(final Context context,String message,int gravity,int duration){
        Toast toast = Toast.makeText(context,message,duration);
        toast.setGravity(gravity,0,0);
        toast.show();
    }

}
